/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 *
 */

import { FileSet, TaskInputValue } from '@ohos/hvigor';
import { generateOhosTestTemplate, GenerateOhosTestTemplateParam } from '@ohos/hvigor-arkts-compose';
import path from 'path';

import { CoreProjectModelImpl } from '../../model/project/core-project-model-impl.js';
import { TaskNames } from '../common/task-names.js';
import { TargetTaskService } from '../service/target-task-service.js';
import { OhosModuleTask } from '../task/ohos-module-task.js';

/**
 * 不依赖DevEco Studio的单元测试构建任务的前置任务
 *
 * @since 2024/05/16
 */
export class GenerateOhosTestTemplate extends OhosModuleTask {
  constructor(taskService: TargetTaskService) {
    super(taskService, TaskNames.Task.GENERATE_OHOS_TEST_TEMPLATE);
  }

  private getParams(): GenerateOhosTestTemplateParam {
    const sourceRoot = this.pathInfo.getModuleBuildIntermediates();
    const isCrossPlatform = (this.projectModel as CoreProjectModelImpl).isCrossplatformProject();
    const apiVersion = this.compileApiVersion;

    return {
      sourceRoot: sourceRoot,
      isCrossPlatform: isCrossPlatform,
      apiVersion: apiVersion,
    };
  }

  declareOutputFiles(): FileSet {
    const fileSet = super.declareOutputFiles();
    fileSet.addEntry(path.resolve(this.pathInfo.getModuleBuildIntermediates(), 'src/ohosTest'), { isDirectory: true });
    return fileSet;
  }

  declareInputs(): Map<string, TaskInputValue> {
    const map = super.declareInputs();
    const params = this.getParams();

    (Object.keys(params) as Array<keyof typeof params>).forEach((key) => {
      const value = params[key];

      if (typeof value !== 'undefined') {
        map.set(key.toString(), value);
      }
    });

    return map;
  }

  async doTaskAction() {
    generateOhosTestTemplate(this.getParams());
  }

  initTaskDepends() {
    // do nothing
  }
}
